from requests.utils import requote_uri


def kibana6_log_app_url(schema: str, host: str, port: int, index_pattern_id: str, filter_fields_app,
                        cst_begin_time: str, cst_end_time: str, filter_log_level: str = "error",
                        prefix_route: str = '/', exclude_keywords: list = None):
    # kibana7版本
    # negate:!f (否定:false 过滤条件)
    url = []
    # kibana_url = f"https://kibana.wolaidai.com/app/kibana#/discover?_g=(refreshInterval:(pause:!t,value:0),time:(from:'{cst_begin_time}',mode:absolute,to:'{cst_end_time}'))&_a=(columns:!(message),filters:!(('$state':(store:appState),"
    kibana_url = f"{schema}://{host}:{port}{prefix_route}app/kibana#/discover?_g=(refreshInterval:(pause:!t,value:0),time:(from:'{cst_begin_time}',mode:absolute,to:'{cst_end_time}'))&_a=(columns:!(message),filters:!(('$state':(store:appState),"
    filter_log_level = f"meta:(alias:!n,disabled:!f,index:'{index_pattern_id}',key:level,negate:!f,params:(query:error,type:phrase),type:phrase,value:{filter_log_level}),query:(match:(level:(query:{filter_log_level},type:phrase)))),('$state':(store:appState),"
    filter_fields_app = f"meta:(alias:!n,disabled:!f,index:{index_pattern_id},key:fields.app,negate:!f,params:(query:{filter_fields_app},type:phrase),type:phrase,value:{filter_fields_app}),query:(match:(fields.app:(query:{filter_fields_app},type:phrase))))"
    url.append(kibana_url)
    url.append(filter_log_level)
    url.append(filter_fields_app)
    if exclude_keywords:
        url.append(",('$state':(store:appState),")
        quote_exclude_keywords = [requote_uri(item) for item in exclude_keywords]
        # negate:!t (否定:true 排除条件)
        for idx, exclude_keyword in enumerate(quote_exclude_keywords):
            # 最后一行拼接
            if idx == len(quote_exclude_keywords) - 1:
                exclude_quote_message = f"meta:(alias:!n,disabled:!f,index:{index_pattern_id},key:message,negate:!t,params:(query:'{exclude_keyword}',type:phrase),type:phrase,value:'{exclude_keyword}'),query:(match:(message:(query:'{exclude_keyword}',type:phrase))))"
                url.append(exclude_quote_message)
            else:
                exclude_quote_message = f"meta:(alias:!n,disabled:!f,index:{index_pattern_id},key:message,negate:!t,params:(query:'{exclude_keyword}',type:phrase),type:phrase,value:'{exclude_keyword}'),query:(match:(message:(query:'{exclude_keyword}',type:phrase)))),('$state':(store:appState),"
                url.append(exclude_quote_message)
    url.append(f"),index:{index_pattern_id},interval:auto,query:(language:lucene,query:''),sort:!('@timestamp',desc))")
    return ''.join(url)


def kibana7_log_app_url(schema: str, host: str, port: int, index_pattern_id: str, filter_fields_app,
                        cst_begin_time: str, cst_end_time: str, filter_log_level: str = "error",
                        prefix_route: str = '/', exclude_keywords: list = None):
    # kibana7版本
    # negate:!f (否定:false 过滤条件)
    url = []
    # kibana_url = f"http://106.52.172.23:5601/app/discover#/?_g=(filters:!(),refreshInterval:(pause:!t,value:0),time:(from:'{cst_begin_time}',to:'{cst_end_time}'))&_a=(columns:!(_source),filters:!(('$state':(store:appState),"
    kibana_url = f"{schema}://{host}:{port}{prefix_route}app/discover#/?_g=(filters:!(),refreshInterval:(pause:!t,value:0),time:(from:'{cst_begin_time}',to:'{cst_end_time}'))&_a=(columns:!(_source),filters:!(('$state':(store:appState),"
    filter_log_level = f"meta:(alias:!n,disabled:!f,index:'{index_pattern_id}',key:level,negate:!f,params:(query:{filter_log_level}),type:phrase),query:(match_phrase:(level:{filter_log_level}))),('$state':(store:appState),"
    filter_fields_app = f"meta:(alias:!n,disabled:!f,index:'{index_pattern_id}',key:fields.app,negate:!f,params:(query:{filter_fields_app}),type:phrase),query:(match_phrase:(fields.app:{filter_fields_app})))"
    url.append(kibana_url)
    url.append(filter_log_level)
    url.append(filter_fields_app)
    if exclude_keywords:
        url.append(",('$state':(store:appState),")
        quote_exclude_keywords = [requote_uri(item) for item in exclude_keywords]
        # negate:!t (否定:true 排除条件)
        for idx, exclude_keyword in enumerate(quote_exclude_keywords):
            # 最后一行拼接
            if idx == len(quote_exclude_keywords) - 1:
                exclude_quote_message = f"meta:(alias:!n,disabled:!f,index:'{index_pattern_id}',key:message,negate:!t,params:(query:'{exclude_keyword}'),type:phrase),query:(match_phrase:(message:'{exclude_keyword}')))"
                url.append(exclude_quote_message)
            else:
                exclude_quote_message = f"meta:(alias:!n,disabled:!f,index:'{index_pattern_id}',key:message,negate:!t,params:(query:'{exclude_keyword}'),type:phrase),query:(match_phrase:(message:'{exclude_keyword}'))),('$state':(store:appState),"
                url.append(exclude_quote_message)
    url.append(f"),index:'{index_pattern_id}',interval:auto,query:(language:lucene,query:''),sort:!())")
    return ''.join(url)


if __name__ == '__main__':
    res = kibana7_log_app_url(schema="https", host="h5.ifastps.com.cn", port=443,
                              index_pattern_id='4732a5f0-0d80-11ed-b9b5-31aeac123002',
                              filter_fields_app="ifast-user", cst_begin_time="2022-08-02 10:00:00",
                              cst_end_time="2022-08-03 11:00:00", filter_log_level="info",
                              prefix_route="/wlb/devops/", exclude_keywords=[])
    print(res)
